package com.simba.filter;

import cn.hutool.core.util.StrUtil;
import com.simba.system.service.OceanUserDetailService;
import com.simba.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwtToken过滤器
 *
 * @author K. L. Mao
 * @create 2019/1/11
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private OceanUserDetailService oceanUserDetailService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authhead = request.getHeader(jwtTokenUtil.getTokenHeader());
        String tokenHead = jwtTokenUtil.getTokenHead();
        //存在token
        if (!StrUtil.isEmpty(authhead) && authhead.startsWith(tokenHead)) {
            String token = authhead.substring(tokenHead.length());
            //log.info("请求中存在token，检查是否过期:"+jwtTokenUtil.isTokenExpired(token));
            String username = jwtTokenUtil.getUserNameFromToken(token);
            log.info("当前登录鉴权过滤器中用户：" + username);
            //存在用户名但未登陆
            if (!StrUtil.isEmpty(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                    //进行登录
                    UserDetails userDetails = oceanUserDetailService.loadUserByUsername(username);
                    //验证token是否有效，重新设置用户对象
                    if (jwtTokenUtil.validateToken(token, userDetails)) {
                        log.info("校验token合法，将用户信息存入authentication，方便后续校验！");
                        // 将用户信息存入 authentication，方便后续校验
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }else {
                        request.setAttribute("errorMessage","token失效，请重新登录！");
                    }
                }

        }else {
            log.info(request.getRequestURI()+"请求Header中不存在合法的token信息！");
            request.setAttribute("errorMessage","请求信息中没有合法token信息，请重新登录！");
        }
        //校验之后要放行
        chain.doFilter(request, response);
    }
}